import {
  defineStore
} from 'pinia'

import {
  ref
} from 'vue'

export const menuStore = defineStore('menu', () => {

  const getLocalStorageMenus = () => {
    try {
      return JSON.parse(localStorage.getItem('_third_menu'))
    } catch (e) {
      return []
    }
  }

  const menus = ref(getLocalStorageMenus())


  const setMenu = (menu) => {
    menus.value = menu || []
    localStorage.setItem('_third_menu', JSON.stringify(menu))
  }

  const getMenu = (menus, pageUrl) => {
    for (const menu of menus) {
      if (menu.pageUrl === pageUrl) {
        return {
          ...menu,
          pages: null
        }
      }
      if (menu.pages) {
        let subMenu = getMenu(menu.pages, pageUrl)
        if (subMenu) return subMenu
      }
    }
  }
  const hasAuthorize = (pageUrl) => {
    const ms = menus.value
    return getMenu(ms, pageUrl)
  }

  return {
    menus,
    setMenu,
    hasAuthorize
  }
})
